import React, { useEffect, useState } from "react";
import "./less/MyHeader.less";
import { Menu, Dropdown, message } from "antd";
import { DownOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

const logo = require("../assets/logo.png");
const default_avatar = require("../assets/admin.png");

export default function MyHeader() {
  const [avatar, setAvatar] = useState(default_avatar);
  const [username, setUsername] = useState("匿名用户");
  const navigate = useNavigate();

  //componentDidMount
  useEffect(() => {
    // 虽然已经在componentDidMount拿到了用户数据，但是没办法让它更新，
    // 只能通过刷新页面去更新
    // 需要利用key来刷新dom 使用redux
    let avatar1 =
      process.env.SERVER_HOST_PORT + "/" + localStorage.getItem("cms-avatar") ||
      default_avatar;
    let username1 = localStorage.getItem("cms-username") || "匿名用户";
    setAvatar(avatar1);
    setUsername(username1);
  }, []);

  //点击了修改资料
  const goMeans = () => {
    let token = localStorage.getItem("cms-token");
    if (token) {
      navigate("/means");
    } else {
      //给出提示，并跳转登录页
      message.warning("登录失效,请重新登录", 1.5);
      setTimeout(() => {
        navigate("/login");
      }, 1500);
    }
  };

  //退出登录
  const logout = () => {
    localStorage.removeItem("cms-token");
    localStorage.removeItem("cms-username");
    localStorage.removeItem("cms-avatar");
    message.warning("即将跳转登录页", 1.5);
    setTimeout(() => {
      navigate("/login");
    }, 1500);
  };

  const menu = (
    <Menu>
      <Menu.Item key='1' onClick={goMeans}>
        修改资料
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key='2' onClick={logout}>
        退出登录
      </Menu.Item>
    </Menu>
  );
  return (
    <header>
      <img src={logo} height={70} alt='logo' />
      <Dropdown overlay={menu}>
        <a
          className='ant-dropdown-link'
          href='!#'
          onClick={(e) => e.preventDefault()}
        >
          <img
            src={avatar}
            width={36}
            style={{ borderRadius: "10%", marginRight: "15px" }}
            alt=''
          />
          <span style={{ marginRight: "10px" }}>{username}</span>
          <DownOutlined />
        </a>
      </Dropdown>
    </header>
  );
}
